package mobile.android.portal.ui;

import java.net.ConnectException;

import mobile.android.portal.util.Functions;
//import java.util.logging.Handler;

//import lk.icta.mobile.apps.postalcode.ui.PostalCodeActivity.DivisionList;
import mobile.android.portal.R;
import mobile.android.portal.obj.Categories;
import mobile.android.portal.obj.ProductByProductId;
import mobile.android.portal.obj.ProductsByCategory;
import mobile.android.portal.webservice.BusinessPortalWebService;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.os.Handler;

public class BrowseProductActivity extends Activity {

	// declare GUI components
	Spinner select_category_spinner;
	Spinner select_manufacturer_spinner;
	Spinner select_product_spinner;

	Handler category_spinner_handler;
	Handler product_spinner_handler;

	Categories categories;
	ProductsByCategory productsByCategory;
	ProductByProductId productByProductId;

	/* declaring progress dialog */
	ProgressDialog progressDialog;

	/*
	 * Declaring alert dialog to indicate if it is not possible to connect with
	 * the web service
	 */
	AlertDialog connectionFailedAlert;
	/* Declaring alert dialog to indicate if user has entered invalid input data */
	AlertDialog userInputValidateAlert;

	/* Variable to store the id of the selected category */
	public static int selectedCategoryId;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_browse_products);

		// initialize GUI components
		select_category_spinner = (Spinner) findViewById(R.id.spinner_select_category);
		select_product_spinner = (Spinner) findViewById(R.id.spinner_select_product);

		progressDialog = Functions.getProgressDialog(this, "Please wait...");

		/* Calls the web service to load all divisions from the data base */
		new WSGetAllCategories().execute(null, null, null);

		category_spinner_handler = new Handler() {
			public void handleMessage(Message message) {

				if (message.what != -1) {

					final CategoryList categoryList[] = new CategoryList[categories
							.getCategoryNames().length + 1];

					categoryList[0] = new CategoryList("",
							"-- Select Category --");

					for (int i = 1; i < categoryList.length; i++) {
						categoryList[i] = new CategoryList(
								categories.getCategoryIds()[i - 1],
								categories.getCategoryNames()[i - 1]);
						Log.v("divisionName : ", categoryList[i].getValue());
					}

					/* Setting key - value pairs to divisionSpinner */
					ArrayAdapter<CategoryList> categoryAdapter = new ArrayAdapter<CategoryList>(
							BrowseProductActivity.this,
							android.R.layout.simple_spinner_item, categoryList);
					select_category_spinner.setAdapter(categoryAdapter);
					progressDialog.dismiss();

					/*
					 * Setting OnItemSelected listeners. if the selected value
					 * of divisionSpinner is null, load an empty list for
					 * postOfficeSpinner. Otherwise load the post offices which
					 * belongs to the selected division.
					 */
					select_category_spinner
							.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

								public void onItemSelected(
										AdapterView<?> parent, View view,
										int position, long id) {
									// postalCodeEditText.setText(null);

									Log.v("test", "test");
									/*
									 * Getting the selected value of the
									 * division list
									 */
									CategoryList selectedCategory = categoryList[position];

									/*
									 * If value of selected item is not null,
									 * assign it to selectedDivisionId.
									 * Otherwise assign it to -1
									 */

									Log.v("selectedCat",
											selectedCategory.getValue());

									if (!selectedCategory.getValue().equals("")) {
										selectedCategoryId = Integer
												.parseInt(selectedCategory
														.getValue());

									} else {
										selectedCategoryId = -1;
									}

									/*
									 * If selectedCategoryId != -1, calls the
									 * web service to retrieve products of the
									 * selected category. Otherwise returns an
									 * empty list of products.
									 */

									if (selectedCategoryId != -1) {

										new WSGetProductByCategory().execute(
												null, null, null);

										progressDialog = Functions
												.getProgressDialog(
														BrowseProductActivity.this,
														"Please wait...");

										product_spinner_handler = new Handler() {

											public void handleMessage(
													Message message) {

												/*
												 * If it is possible to connect
												 * with the server loads
												 * products ist to product
												 * Spinner. Otherwise display
												 * connection failed alert
												 * message
												 */
												if (message.what != -1) {
													final ProductList[] productList = new ProductList[productsByCategory
															.getProductNames().length + 1];

													productList[0] = new ProductList(
															"",
															"-- Select Product --");

													for (int i = 1; i < productList.length; i++) {

														productList[i] = new ProductList(
																productsByCategory
																		.getProductIds()[i - 1],
																productsByCategory
																		.getProductNames()[i - 1]);
													}

													/*
													 * Setting key - value pairs
													 * to products spinner.
													 */
													ArrayAdapter<ProductList> productAdapter = new ArrayAdapter<ProductList>(
															BrowseProductActivity.this,
															android.R.layout.simple_spinner_item,
															productList);

													select_product_spinner
															.setAdapter(productAdapter);
													progressDialog.dismiss();

												} else {

													/*
													 * Display connection failed
													 * alert message
													 */
													connectionFailedAlert = Functions
															.getConnectionFailedAlert(
																	BrowseProductActivity.this,
																	"Sorry. \nUnable to provide the service this time. Please try again latter.");
												}
											}
										};
									} else {

										/*
										 * Set an empty list of post offices to
										 * postOfficeSpinner while loading
										 * division list to divisionSpinner
										 */
										String[] productEmptyList = { "-- Select Product --" };

										ArrayAdapter<String> productEmptyAdapter = new ArrayAdapter<String>(
												BrowseProductActivity.this,
												android.R.layout.simple_spinner_item,
												productEmptyList);

										select_product_spinner
												.setAdapter(productEmptyAdapter);

										progressDialog.dismiss();
									}

								}

								public void onNothingSelected(
										AdapterView<?> parent) {

								}
							});

				} else {

					/* Display connection failed alert message */
					connectionFailedAlert = Functions
							.getConnectionFailedAlert(
									BrowseProductActivity.this,
									"Sorry. \nUnable to provide the service this time. Please try again latter.");

				}
			}
		};

	}

	public void onSubmitButtonClick(View v) {

		if ((int) select_category_spinner.getSelectedItemPosition() != 0) {
			Intent resultSceen = new Intent(this, SearchResultActivity.class);
			
			//String selectedCategory = ;

			Log.v("selectedCategory", select_category_spinner.getSelectedItem().toString());
			resultSceen.putExtra("category_name",  select_category_spinner.getSelectedItem().toString());

			if (select_product_spinner.getSelectedItemPosition() != 0) {

				// Log.v("selectedId",
				// Long.toString(select_product_spinner.getSelectedItemId()));

				resultSceen
						.putExtra("product_id", productsByCategory
								.getProductIds()[(int) select_product_spinner
								.getSelectedItemId() - 1]);
				startActivity(resultSceen);

			} else {
				/* Display user input validation alert message */
				userInputValidateAlert = Functions.getUserInputValidateAlert(
						BrowseProductActivity.this, "Please select a product",
						"Warning!");
			}

		} else {

			/* Display user input validation alert message */
			userInputValidateAlert = Functions.getUserInputValidateAlert(
					BrowseProductActivity.this, "Please select a category",
					"Warning!");

		}

		// Intent searchResultScreen = new Intent(this,
		// SearchResultActivity.class);
		// startActivity(searchResultScreen);
	}

	/*
	 * Asynchronous back ground process to retrieve the all divisions from the
	 * data base. If an exception occured sends and empty message to the web
	 * service client
	 */
	class WSGetAllCategories extends AsyncTask<Object, Object, Object> {

		@Override
		protected Object doInBackground(Object... params) {
			try {
				Log.v("calling - ", "getAllCategories");
				categories = BusinessPortalWebService.getAllCategories();
				Log.v("result - ", categories.toString());
				category_spinner_handler.sendMessage(category_spinner_handler
						.obtainMessage());
				return null;

			} catch (ConnectException e) {
				/*
				 * Sends an empty message to the web service client if an
				 * ConnectException occurred
				 */
				category_spinner_handler.sendEmptyMessage(-1);
				progressDialog.dismiss();
				Log.i("ConnectException", "ConnectException occured");
				e.printStackTrace();

			} catch (Exception e) {
				// TODO Auto-generated catch block
				// Send an empty message if an exception occurred
				category_spinner_handler.sendEmptyMessage(-1);
				progressDialog.dismiss();
				Log.i("Exception", "Exception occured");
				e.printStackTrace();
			}
			return null;
		}
	}

	/*
	 * Asynchronous back ground process to retrieve the post offices of the
	 * selected division. If an exception occurred sends and empty message to
	 * the web service client
	 */
	class WSGetProductByCategory extends AsyncTask<Object, Object, Object> {

		@Override
		protected Object doInBackground(Object... params) {
			try {
				productsByCategory = BusinessPortalWebService
						.getProductByCategory(selectedCategoryId);
				product_spinner_handler.sendMessage(product_spinner_handler
						.obtainMessage());
				return null;

			} catch (ConnectException e) {
				// TODO: handle exception
				// Send an empty message if an ConnectException occurred
				product_spinner_handler.sendEmptyMessage(-1);
				progressDialog.dismiss();
				Log.i("ConnectException", "ConnectException occured");
				e.printStackTrace();

			} catch (Exception e) {
				// TODO: handle exception
				// Send an empty message if an exception occurred
				product_spinner_handler.sendEmptyMessage(-1);
				progressDialog.dismiss();
				Log.i("Exception", "Exception occured");
				e.printStackTrace();
			}
			return null;
		}
	}

	class CategoryList {
		public CategoryList(String value, String spinnerText) {
			this.spinnerText = spinnerText;
			this.value = value;
		}

		public String getSpinnerText() {
			return spinnerText;
		}

		public String getValue() {
			return value;
		}

		public String toString() {
			return spinnerText;
		}

		String spinnerText;
		String value;
	}

	class ProductList {
		public ProductList(String value, String spinnerText) {
			this.spinnerText = spinnerText;
			this.value = value;
		}

		public String getSpinnerText() {
			return spinnerText;
		}

		public String getValue() {
			return value;
		}

		public String toString() {
			return spinnerText;
		}

		String spinnerText;
		String value;
	}

}
